package com.zhiwang.planet.mvp.p

import android.graphics.BitmapFactory
import com.zhiwang.planet.di.ActivityScope
import com.zhiwang.planet.mvp.v.GraphView
import com.zhiwang.planet.mvp.v.RegisterView
import com.zhiwang.planet.mvp.v.SmsCodeView
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.mvvm.model.request.SmsCodeRequest
import com.zhiwang.planet.mvvm.model.request.RegisterRequest
import com.zhiwang.planet.util.androidSchedule
import com.zhiwang.planet.util.responseFunc
import com.zhiwang.planet.util.responseVoidFunc
import javax.inject.Inject

@ActivityScope
class RegisterPresenter @Inject constructor(var restApi: RestApi) {

    lateinit var smsCodeView: SmsCodeView

    lateinit var graphView: GraphView

    lateinit var registerView: RegisterView

    //获取注册的图形验证码
    fun getRegisterGraphCode(random: String) {
//        val graphCodeRequest = GraphRequest(random)
        restApi.getGraphCode(random, "app_reg")
                .androidSchedule()
                .subscribe({
                    val bitmap = BitmapFactory.decodeStream(it.byteStream())
                    graphView.onGraphCodeLoad(bitmap)
                }, {
                    graphView.onError(it)
                }, {

                })


    }

    /**
     * [randomStr]获取图新验证码时候使用的randomStr
     *[graphCode]图形验证码
     * [phone] 手机号
     */
    fun getRegisterSmsCode(randomStr: String, graphCode: String, phone: String) {
        val smsCodeRequest = SmsCodeRequest(phone, graphCode, randomStr)
        smsCodeRequest.setTypeRegister()
        restApi.getSmsCode(smsCodeRequest)
                .androidSchedule()
                .responseVoidFunc()
                .subscribe({

                }, {
                    smsCodeView.onError(it)
                }, {
                    smsCodeView.onSmsSend()
                })
    }

    fun register(sms: String, phone: String, pwd: String) {
        val registerRequest = RegisterRequest(sms, phone, pwd)
        restApi.register(registerRequest)
                .androidSchedule()
                .responseFunc()
                .subscribe({
                    registerView.onRegisterSuccess()
                }, {
                    registerView.onError(it)
                }, {
                })

    }

}